package com.xuj.recyclerviewdemo.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.xuj.recyclerviewdemo.R;

import java.util.ArrayList;
import java.util.List;


/**
 * 用于RecyclerView的普通加载
 */
public class SimpleAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {


    private Context mContext;
    private LayoutInflater mInflater;
    private List<String> mDatas;
    private OnItemClickListener mListener;

    public SimpleAdapter(Context context) {
        this.mContext = context;
        mInflater = LayoutInflater.from(mContext);
        mDatas = new ArrayList<String>();

    }


    public void setOnItemClickListener(OnItemClickListener li) {
        mListener = li;
    }


    public void addDatas(List<String> datas) {
        mDatas.addAll(datas);
        notifyDataSetChanged();
    }


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View layout = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
        return new Holder(layout);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, final int position) {

        if (viewHolder instanceof Holder) {
            ((Holder) viewHolder).tv.setText(mDatas.get(position));
            if (mListener != null) {
                viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mListener.onItemClick(v, position);
                    }
                });
                viewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {

                    @Override
                    public boolean onLongClick(View view) {
                        mListener.onItemLongClick(view,position);
                        return false;
                    }
                });
            }
        }
    }


    @Override
    public int getItemCount() {
        return mDatas.size();
    }


    class Holder extends RecyclerView.ViewHolder {

        TextView tv;

        public Holder(View view) {
            super(view);
            tv = (TextView) view.findViewById(R.id.textView);
        }
    }
}
